/*
 * StockNew.java
 * 
 * Copyright (c) 2012 Supin P Surendran <supinps@gmail.com>.
 * 
 * This file is part of InventoryMan.
 * 
 * InventoryMan is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * InventoryMan is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with InventoryMan.  If not, see <http ://www.gnu.org/licenses/>.
 */

/*
 * StockNew.java
 *
 * Created on 23 Dec, 2012, 4:12:47 AM
 */

package InventoryMan;

import java.awt.event.ActionEvent;
import java.sql.SQLException;
import javax.swing.event.ListSelectionEvent;

/**
 *
 * @author Supin P Surendran <supinps@gmail.com>
 */
public class StockNew extends javax.swing.JInternalFrame {

    /** Creates new form StockNew
     * @param conn Connection to the database
     */
    @SuppressWarnings("static-access")
    public StockNew(java.sql.Connection conn) {
        comboItem=new javax.swing.DefaultComboBoxModel();
        tableItem=new javax.swing.table.DefaultTableModel(new Object[]{"Code","Item","Stock"}, 0);
        imConnection=conn;
        initComponents();
        ac.decorate(CmbItem);
        CmbItem.setModel(comboItem);
        TblItem.setModel(tableItem);
        initDataSet();
        initListeners();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        CmbItem = new org.jdesktop.swingx.JXComboBox();
        jLabel2 = new javax.swing.JLabel();
        TxtItemName = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        TxtAvailableStock = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        TxtNewStock = new javax.swing.JTextField();
        BnSave = new javax.swing.JButton();
        BnCancel = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        TblItem = new javax.swing.JTable();

        setTitle("New Stock");
        setFrameIcon(new javax.swing.ImageIcon(getClass().getResource("/Resources/icon_small.png"))); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel1.setText("Item Code :");

        CmbItem.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        jLabel2.setText("Item Name :");

        jLabel3.setText("Available Stock :");

        jLabel4.setText("New Stock Value :");

        BnSave.setText("Save");
        BnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BnSaveActionPerformed(evt);
            }
        });

        BnCancel.setText("Cancel");
        BnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BnCancelActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(635, Short.MAX_VALUE)
                .addComponent(BnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(56, 56, 56)
                .addComponent(BnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel3)
                        .addComponent(jLabel1))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(CmbItem, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(TxtAvailableStock, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(jLabel2)
                        .addComponent(jLabel4))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(TxtNewStock, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE)
                        .addComponent(TxtItemName, javax.swing.GroupLayout.DEFAULT_SIZE, 329, Short.MAX_VALUE))
                    .addContainerGap()))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(141, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(BnCancel)
                    .addComponent(BnSave))
                .addContainerGap())
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(CmbItem, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel2)
                        .addComponent(TxtItemName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(45, 45, 45)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(TxtAvailableStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel4)
                        .addComponent(TxtNewStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(69, Short.MAX_VALUE)))
        );

        TblItem.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(TblItem);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 871, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BnCancelActionPerformed
        this.dispose();
    }//GEN-LAST:event_BnCancelActionPerformed

    private void BnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BnSaveActionPerformed
        int newStock=Integer.parseInt(TxtAvailableStock.getText())+Integer.parseInt(TxtNewStock.getText());
        try {
            prepStmt = imConnection.prepareStatement("UPDATE item SET stock=? WHERE code=?");
            prepStmt.setInt(1, newStock);
            prepStmt.setInt(2, Integer.parseInt(comboItem.getSelectedItem().toString()));
            prepStmt.executeUpdate();
            this.dispose();
        } catch (SQLException ex) {
            javax.swing.JOptionPane.showMessageDialog(this, ex.toString());
        }
    }//GEN-LAST:event_BnSaveActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BnCancel;
    private javax.swing.JButton BnSave;
    private org.jdesktop.swingx.JXComboBox CmbItem;
    private javax.swing.JTable TblItem;
    private javax.swing.JTextField TxtAvailableStock;
    private javax.swing.JTextField TxtItemName;
    private javax.swing.JTextField TxtNewStock;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables

    //Manually Declared Variables
    java.sql.Connection imConnection;
    java.sql.Statement stmt;
    java.sql.PreparedStatement prepStmt;
    java.sql.ResultSet reply;
    //DataModels for table and Combobox
    javax.swing.DefaultComboBoxModel comboItem;
    javax.swing.table.DefaultTableModel tableItem;
    javax.swing.ListSelectionModel tableSelection;
    int rowIndex;
    org.jdesktop.swingx.autocomplete.AutoCompleteDecorator ac;
    //End of Declarations

    /**
     * fetches initial data from the table item
     * and populates combobox and table
     * event listeners are also initialized
     */
    private void initDataSet() {
        try {
            stmt=imConnection.createStatement();
            reply=stmt.executeQuery("SELECT item.code,item.name,item.stock FROM item");
            int code;
            String name;
            int stock;
            while(reply.next()) {
                code=reply.getInt("code");
                name=reply.getString("name");
                stock=reply.getInt("stock");
                comboItem.addElement(code);
                tableItem.addRow(new Object[]{code,name,stock});
            }
        }catch(java.sql.SQLException ex) {
            javax.swing.JOptionPane.showMessageDialog(this, ex.toString());
        }
    }

    private void initListeners() {
        tableSelection=TblItem.getSelectionModel();
        tableSelection.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        tableSelection.addListSelectionListener(new javax.swing.event.ListSelectionListener() {

            public void valueChanged(ListSelectionEvent e) {
                rowIndex=tableSelection.getLeadSelectionIndex();
                comboItem.setSelectedItem(tableItem.getValueAt(rowIndex, 0));
            }
        });
        CmbItem.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(ActionEvent e) {
                try {
                    reply.absolute(CmbItem.getSelectedIndex() + 1);
                    TxtItemName.setText(reply.getString("name"));
                    TxtAvailableStock.setText(Integer.toString(reply.getInt("stock")));
                } catch (SQLException ex) {
                    javax.swing.JOptionPane.showMessageDialog(null, ex.toString());
                }

            }
        });
    }
    
}
